/*
 * @Author: XiaoFeng Chen 
 * @Date: 2018-09-25 15:28:41 
 * @Last Modified by: XiaoFeng Chen
 * @Last Modified time: 2018-11-05 14:08:01
 * @Desc 根据docs目录下的文件生成index.vue，menus.json，pages.js，
 */


// var express = require('express');
var fs = require('fs');
var path = require('path');

//https://ejs.bootcss.com/
var ejs = require('ejs') //编译器

//起个服务实施更新，难点太多，也不好用，暂时放弃
// var app = express();
// var port = 8888;

// var allowCrossDomain = function (req, res, next) {
//   res.header('Access-Control-Allow-Origin', '*');//自定义中间件，设置跨域需要的响应头。
//   next();
// };

// 读取docs下面文件夹名称，创建目录 menu.json
var docsTemplate = path.resolve(__dirname, './template');
// 读到页面模板文件
var templateStr = fs.readFileSync(docsTemplate, 'UTF-8');

var cachePath=path.resolve(__dirname,'../.cache');
//菜单结构，basic>[]
function render() {
  var docsPath= path.join(__dirname, '..', './.cache/docs')
  var files = fs.readdirSync(docsPath);
  var ndirs = [];
  files.forEach(function (f, index) {

    var item = {
      name: f,
      children: []
    }

    var fpath = path.resolve(docsPath, f);
    var cfiles = fs.readdirSync(fpath);
    cfiles.forEach((cf) => {
      var cfpath = path.resolve(fpath, cf);
      if (fs.statSync(cfpath).isDirectory()) {
        item.children.push({
          name: cf,
          path: cfpath
        })
      }
    });
    ndirs.push(item)
  });
  // console.log(JSON.stringify(ndirs));

  //写目录
  var menus = [],
    webpacks = [];
  ndirs.forEach(fmenu => {

    var m = {
      pagename: fmenu.name,
      children: []
    }

    fmenu.children.forEach(f => {
      var fpath = f.path,
          npath=path.resolve(fpath, 'index.js');
      delete require.cache[npath]
      try {
        var ijson = require(npath);  
      } catch (error) {
        return;
      }
      

      //序列化readme ，不序列化，写readme会相当麻烦
      if (!ijson.examples) {
        ijson.examples = []
      }
      ijson.intro = encodeURIComponent(ijson.intro || '');
      ijson.examples.forEach(function (it) {
        it.readme = encodeURIComponent(it.readme)
      });
      
      //生成index.vue
      var t = ejs.render(templateStr, ijson, {
        context: ijson
      })
      fs.writeFileSync(path.resolve(fpath, 'index.vue'), t)

      //相对目录
      var nfpath = fpath.replace(docsPath, '').slice(1).replace(/\\/, '/');

      webpacks.push(`${ijson.name}:()=>import(/* webpackChunkName: ${ijson.name} */ './docs/${nfpath}/index.vue')`)

      m.children.push({
        pagename: ijson.name
      })
    });
    menus.push(m)

  });
  //生成菜单

  menus = JSON.stringify(menus);

  //生成菜单文件
  // return {
  //   menus: '{"data":' + menus + '}',
  //   pages: 'export default {\n' + webpacks.join(',\n') + '\n}'
  // }
  // var renderResult = docRender(cachePath + '\\docs');
  fs.writeFileSync(cachePath + '\\.doc.menus.json', '{"data":' + menus + '}')
  //生成组件文件
  fs.writeFileSync(cachePath + '\\.doc.pages.js', 'export default {\n' + webpacks.join(',\n') + '\n}')
  //生成组件文件
}

// render('E:\\html\\leave_work_on_time\\exampleServer-demo\\exampleServer\\.cache\\docs')

module.exports = {
  render
}

// app.use(allowCrossDomain);//运用跨域的中间件

// app.listen(port,function(){
//   console.log('文档静态资源服务已开启，热更新依赖此服务，请和webpack-dev-server 服务同时关闭。')
